<template>
    <main-header />
    <a-button class="btn" type="primary" @click="open(false)">添加分类</a-button>
    <a-table
        :columns="columns"
        :row-key="(record) => record.id"
        @expand="zi"
        :expandedRowKeys="expandedRowKeys"
        :data-source="tableData"
    >
        <template #bodyCell="{ column, text, record }">
            <template v-if="column.dataIndex === 'caozuo'">
                <a-button type="link" @click="open(true, record)">编辑</a-button>
            </template>
            <template v-if="column.dataIndex === 'status'">
                <a-switch
                    v-model:checked="record.status"
                    checked-children="已启用"
                    un-checked-children="未启用"
                    @change="onChange(record)"
                />
            </template>
        </template>
    </a-table>
    <a-modal
        v-model:visible="visible"
        :title="!isEdit ? '增加分类' : '修改分类'"
        :footer="false"
        @cancel="reset"
    >
        <a-form
            v-if="visible"
            :model="categoryForm"
            ref="categoryFormRef"
            layout="vertical"
            @finish="categoryFormFinish"
        >
            <a-form-item name="pid" label="父级分类">
                <a-cascader
                    v-model:value="categoryForm.pid"
                    :options="tableData"
                    placeholder="请选择父级分类,不选择择创建分类"
                    change-on-select
                    :fieldNames="{ label: 'name', value: 'id', children: 'children' }"
                />
            </a-form-item>
            <a-form-item
                name="name"
                label="分类名称"
                :rules="[{ required: true, message: '分类名称' }]"
            >
                <a-input
                    v-model:value="categoryForm.name"
                    allow-clear
                    placeholder="请输入分类名称"
                ></a-input>
            </a-form-item>
            <a-form-item>
                <a-button type="primary" html-type="submit">{{
                    !isEdit ? '增加' : '修改'
                }}</a-button>
                <a-button style="margin-left: 10px" @click="reset">重置</a-button>
            </a-form-item>
        </a-form>
    </a-modal>
</template>

<script setup>
import { onMounted, ref, getCurrentInstance } from 'vue'
import {
    getCategoryListAPI,
    getCategoryInfoAPI,
    addCategoryAPI,
    updateCategoryListAPI,
    changCategoryStatusAPI
} from '@/api/category.js'
const { proxy: _this } = getCurrentInstance()
const columns = [
    { title: '名称', dataIndex: 'name' },
    { title: '状态', dataIndex: 'status' },
    { title: '操作', dataIndex: 'caozuo' }
]
const tableData = ref([])
const getCategory = () => {
    getCategoryListAPI().then((res) => {
        const arr = traversalTree(res)
        tableData.value = arr
    })
}
function traversalTree(arrs) {
    arrs.map((item) => {
        item.status = item.status ? true : false
        if (item.children && item.children.length !== 0) {
            traversalTree(item.children)
        }
    })
    return arrs
}
const expandedRowKeys = ref([])
const zi = (expanded, record) => {
    // 只展开一行
    if (expandedRowKeys.value.length > 0) {
        //进这个判断说明当前已经有展开的了
        //返回某个指定的字符串值在字符串中首次出现的位置，下标为0
        let index = expandedRowKeys.value.indexOf(record.id)
        if (index > -1) {
            //如果出现则截取这个id,1d到1相当于0，针对重复点击一个
            expandedRowKeys.value.splice(index, 1)
        } else {
            //如果没出现则截取所有id,添加点击id，0到1，针对已经有一个展开，点另一个会进入判断
            expandedRowKeys.value.splice(0, expandedRowKeys.value.length)
            expandedRowKeys.value.push(record.id)
        }
    } else {
        //数组长度小于0，说明都没展开，第一次点击，id添加到数组，数组有谁的id谁就展开
        expandedRowKeys.value.push(record.id)
    }
}
onMounted(() => {
    getCategory()
})
const visible = ref(false)
const isEdit = ref(false)
const categoryFormRef = ref()
const categoryForm = ref({
    name: '',
    pid: ''
})
const editId = ref('')
const open = (flag, row) => {
    visible.value = true
    isEdit.value = flag
    if (flag) {
        editId.value = row.id
        getCategoryInfoAPI(row.id).then((res) => {
            categoryForm.value.name = res.name
            if (res.pid === 0) {
                categoryForm.value.pid = ''
            } else {
                categoryForm.value.pid = [res.pid]
            }
        })
    }
}
const categoryFormFinish = async (value) => {
    value.pid = value.pid[0]
    if (isEdit.value) {
        const res = await updateCategoryListAPI(value, editId.value)
    } else {
        const res = await addCategoryAPI(value)
    }
    _this.$message.success(isEdit.value ? '修改成功' : '添加成功')
    visible.value = false
    getCategory()
}
const reset = () => {
    categoryForm.value = {}
    categoryFormRef.value.resetFields()
}
const onChange = (row) => {
    changCategoryStatusAPI(row.id).then((res) => {})
}
</script>
<style scoped lang="scss">
.btn {
    margin: 10px 0;
}
</style>
